package logic

import (
	"context"
	"encoding/json"
	"errors"
	"week_three/car_srv/models"
	car_rpc "week_three/car_srv/proto"
	"week_three/car_srv/service/es"
	"week_three/car_srv/service/mysql"
	"week_three/car_srv/service/redis"
)

func (c *CarRpc) CreateCar(ctx context.Context, in *car_rpc.CreateCarReq) (*car_rpc.CreateCarRes, error) {
	var rr = car_rpc.CreateCarRes{Is: false}
	//mysql
	car, tx, err := mysql.CreateCar(&models.Car{
		Name:    in.Name,
		Price:   int(in.Price),
		Brand:   in.Brand,
		CarType: int(in.CarType),
		Detail:  in.Detail,
	})
	if err != nil {
		tx.Rollback()
		return &rr, err
	}
	//es
	is := es.CreateCarEs(in.Index, car)
	if !is {
		tx.Rollback()
		return &rr, errors.New("es create failed")
	}
	//redis
	err = redis.CreateCar(car)
	if err != nil {
		return &rr, err
	}
	tx.Commit()
	rr.Is = true
	return &rr, nil
	rr.Is = true
	return &rr, nil
}
func (c *CarRpc) CarPriceTop(ctx context.Context, in *car_rpc.CarPriceTopReq) (*car_rpc.CarPriceTopRes, error) {
	is := redis.IsCarPriceKey()
	var list []*car_rpc.CarData
	if is == 0 {
		cars, err := mysql.MysqlToReids()
		if err != nil {
			return &car_rpc.CarPriceTopRes{}, err
		}
		for _, v := range cars {
			err = redis.CreateCar(v)
			if err != nil {
				return &car_rpc.CarPriceTopRes{}, err
			}
			var data = &car_rpc.CarData{
				Name:    v.Name,
				Price:   int32(v.Price),
				Brand:   v.Brand,
				CarType: int32(v.CarType),
				Detail:  v.Detail,
			}
			list = append(list, data)
		}
		return &car_rpc.CarPriceTopRes{
			Data: list,
		}, nil
	}
	res := redis.SearchCarTop()
	for _, v := range res {
		var car *models.Car
		json.Unmarshal([]byte(v), &car)
		var data = &car_rpc.CarData{
			Name:    car.Name,
			Price:   int32(car.Price),
			Brand:   car.Brand,
			CarType: int32(car.CarType),
			Detail:  car.Detail,
		}
		list = append(list, data)
	}
	return &car_rpc.CarPriceTopRes{
		Data: list,
	}, nil
}
func (c *CarRpc) EsSearch(ctx context.Context, in *car_rpc.EsSearchReq) (*car_rpc.EsSearchRes, error) {
	list := es.SearchEs(in.Index, in.Name)
	return &car_rpc.EsSearchRes{
		Data: list,
	}, nil
}
